/**
 * Created by xmgong on 2017/12/16.
 * 商品详情
 */
import React from 'react';
import {connect} from 'react-redux';
import {View, FlatList, Text, TextInput, TouchableOpacity, Image, Dimensions} from 'react-native';
import {naviPush, naviBack} from '../../navigatorApp/actions'
import CLNavigatorHeader from '../../component/CLNavigatorHeader';
import StepInfo from './stepInfo';
import {editRichContent, showLoading, hideLoading, toast} from '../../utils/NativeUtil';
import styles from './styles';
import themeconfig from '../../config/theme';
import {saveProductDetail, submitProduct, getProductDetail} from './actions';

let {width, height} = Dimensions.get('window');
import { NavigationActions } from 'react-navigation'

class ProductDetail extends React.Component {

    static navigationOptions = ({navigation, screenProps}) => {
        const {params = {}} = navigation.state;
        let header = (<CLNavigatorHeader navigation={navigation} title="详情"
                                         rightImage={require('../../image/img_edit_white.png')}
                                         rightAction={params.submit}/>);
        return {header}
    };


    componentDidMount() {
        this.props.navigation.setParams({submit: this.editDetail});

        let params = {
            token: this.props.token,
            id: this.props.navigation.state.params.id
        };
        let self = this;
        getProductDetail(params, function (res) {
            self.hasAduited = res.hasAduited;
            if (self.hasAduited > 0){
                self.setState({buttonTitle: '保存'});
            }
            let goodsDesc = res.goodsDesc;
            let temp = JSON.parse(goodsDesc);
            self.setState({detail: temp});
        });
    }

    constructor(props) {
        super(props);
        this.state = {
            buttonTitle:"提交",
            detail: [],
        };

        this.hasAduited = -1;
        
        this.goodsId = props.navigation.state.params.id;
    }

    editDetail = () => {
        const self = this;
        editRichContent({
            title: "编辑",
            filetag: "product",
            value: JSON.stringify(this.state.detail)
        }, (value) => {
            let temp = JSON.parse(value.value);
            self.setState({detail: temp});
            self.saveDetail();
        });
    };

    _renderItem = ({item}) => {
        let itemview;
        if (item.type == 1) {
            itemview = (<Text>{item.value}</Text>);
        } else if (item.type == 2) {
            itemview = (<Image 
                resizeMode={Image.resizeMode.center}
                source={{uri: item.value}} 
                style={{width: width-20, height: 120}}/>)
        }

        return (<View style={{paddingLeft: 10, paddingRight: 10}}>
            {itemview}
        </View>);
    };

    _ListEmptyComponent = () => {
        return (<View style={{flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center'}}>
            <TouchableOpacity onPress={() => this.editDetail()} style={{flex: 1}}>
                <View style={{
                    width: 120,
                    height: 40,
                    marginTop:40,
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'center',
                    borderColor: themeconfig.maincolor,
                    borderRadius: 3,
                    borderWidth: 1,
                }}>
                    <Text style={{color: themeconfig.maincolor}}>立即编辑</Text>
                </View>
            </TouchableOpacity>
        </View>)
    };

    _ItemSeparatorComponent = () => {
        return (<View style={{height: 5}}/>)
    };

    /**
     * token    token    是
     goodsId    商品id    是
     goodsDesc    商品详情    是
     */
    saveDetail = () => {
        showLoading('正在保存');
        let params = {
            token: this.props.token,
            goodsId: this.goodsId,
            goodsDesc: JSON.stringify(this.state.detail)
        };
        this.props.saveProductDetail(params, function () {
            hideLoading('');
        });
    };


    submitProductAction = () => {
        let params = {
            token: this.props.token,
            goodsId: this.goodsId
        };
        showLoading("正在提交");
        const self = this;

        if (this.hasAduited < 0){
            this.props.submitProduct(params, function () {
                toast('提交完成');
                self.goBack();
            })
        }else{
            toast('保存成功');
            self.goBack();
        }
       
    };

    goBack = () => {
        this.props.naviBack('ProductAdd');
        // if (this.props.is_from_home){
        //     const resetAction = NavigationActions.reset({
        //         index: 0,
        //         actions: [
        //             NavigationActions.navigate({ routeName: 'Home'}),
        //         ]
        //     })
        //     this.props.navigation.dispatch(resetAction)
        // }else{
            // const resetAction = NavigationActions.reset({
            //     index: 1,
            //     actions: [
            //         NavigationActions.navigate({ routeName: 'Home'}),
            //         NavigationActions.navigate({ routeName: 'product'}),
            //     ]
            // });
            // this.props.navigation.dispatch(resetAction)
        // }
    };


    render() {
        return (
            <View style={{flex: 1, flexDirection: 'column'}}>
                <StepInfo backgroundColor='#f8f7f7' step={1} index={3}/>
                <FlatList
                    style={{backgroundColor: 'white', flex: 1}}
                    data={this.state.detail}
                    renderItem={this._renderItem}
                    ItemSeparatorComponent={this._ItemSeparatorComponent}
                    ListEmptyComponent={this._ListEmptyComponent}
                />
                <TouchableOpacity
                    onPress={() => {
                        this.submitProductAction()
                    }}>
                    <View style={styles.submitButton}>
                        <Text style={{
                            color: "white"
                        }}>{this.state.buttonTitle}</Text>
                    </View>
                </TouchableOpacity>
            </View>)
    }
}


const mapStateToProps = (state) => {
    return {
        token: state.mainmodel.token,
        is_from_home:state.mainmodel.is_from_home,
    }
};


const mapDispatchToProps = (dispatch) => {
    return {
        naviPush: (routerName, params) => {
            dispatch(naviPush(routerName, params));
        },
        saveProductDetail: (params, callback) => {
            dispatch(saveProductDetail(params, callback));
        },
        submitProduct: (params, callback) => {
            dispatch(submitProduct(params, callback));
        },
        naviBack: (routeName) => {
            dispatch(naviBack(routeName));
        }
    }
};

export default connect(
    mapStateToProps,
    mapDispatchToProps,
)(ProductDetail);

